package com.haha.keymap.v4;

import com.haha.keymap.v1.CustomColor;
import com.haha.keymap.v1.CustomPoint;
import com.haha.keymap.v1.SkillConfigData;
import com.haha.keymap.v1.SkillInfo;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import org.jnativehook.GlobalScreen;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;

import java.awt.*;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shenlinnan
 * @date 2025/7/20 13:18
 */
public class MainController implements NativeKeyListener {

    private static final String START_WORD = "启动";
    private static final String STOP_WORD = "停止";
    /**
     * 存储所有标签页的映射关系
     */
    private final Map<Tab, ToggleGroup> tabToggleGroupMap = new HashMap<>();
    private SkillConfigData skillConfigData;
    private SkillConfigData skillAoeConfigData;
    private Stage primaryStage;
    private MainApp mainApp;
    @FXML
    private Button startButton;
    @FXML
    private Label stopWord;
    @FXML
    private Label startWord;
    private Robot robot;
    @FXML
    private Label selectedTalentLabel;
    @FXML
    private TabPane classTabPane;
    @FXML
    private ToggleGroup talentToggleGroup;
    /**
     * 存储当前标签页对应的ToggleGroup
     */
    private ToggleGroup currentTalentToggleGroup;
    // 存储当前选择
    private String selectedClass = "猎人";
    private String selectedTalent = "";
    private String selectedVersion = "";

    public void setSkillConfigData(SkillConfigData skillConfigData) {
        this.skillConfigData = skillConfigData;
    }

    public void setSkillAoeConfigData(SkillConfigData skillAoeConfigData) {
        this.skillAoeConfigData = skillAoeConfigData;
    }

    public void setPrimaryStage(Stage primaryStage) {
        this.primaryStage = primaryStage;
    }

    @FXML
    private void handleStartButtonAction() {
        this.setSkillConfigData(CommonUtil.getConfigInfo(selectedTalentLabel.getText()));
        this.setSkillAoeConfigData(CommonUtil.getAoeConfigInfo(selectedTalentLabel.getText()));
        if (skillConfigData == null) {
            showCustomDialog("配置错误", "请先进行配置！");
            return;
        }
        String text = startButton.getText();
        System.out.println(text);
        if (START_WORD.equals(text)) {
            start();
        } else {
            stop();
        }
        System.out.println("start按钮事件处理");
    }

    private void start() {
        startWord.setVisible(true);
        stopWord.setVisible(false);
        startButton.setText("停止");
    }

    private void stop() {
        startWord.setVisible(false);
        stopWord.setVisible(true);
        startButton.setText("启动");
    }

    @FXML
    private void handleConfigButtonAction() {
        if (mainApp != null) {
            mainApp.showConfigDialog();
        } else {
            System.out.println("没有mainApp");
        }
        System.out.println("config按钮事件处理");
    }

    private void showCustomDialog(String title, String message) {
        // 创建新窗口作为对话框
        Stage dialog = new Stage();
        dialog.initModality(Modality.APPLICATION_MODAL);
        dialog.initOwner(primaryStage);
        dialog.setTitle(title);
        // 简洁样式
        dialog.initStyle(StageStyle.UTILITY);

        // 创建对话框内容
        VBox dialogContent = new VBox(15);
        dialogContent.setPadding(new javafx.geometry.Insets(20));
        dialogContent.setAlignment(javafx.geometry.Pos.CENTER);

        // 添加消息文本
        Label messageLabel = new Label(message);
        messageLabel.setStyle("-fx-font-size: 16px;");

        // 添加确定按钮
        Button okButton = new Button("确定");
        okButton.setStyle("-fx-font-size: 14px; -fx-pref-width: 80px;");
        okButton.setOnAction(e -> dialog.close());

        // 添加到布局
        dialogContent.getChildren().addAll(messageLabel, okButton);

        // 设置场景并显示
        Scene dialogScene = new Scene(dialogContent, 300, 150);
        dialog.setScene(dialogScene);
        dialog.show();
    }

    public void setMainApp(MainApp mainApp) {
        this.mainApp = mainApp;
    }

    @Override
    public void nativeKeyTyped(NativeKeyEvent nativeKeyEvent) {

    }

    @Override
    public void nativeKeyPressed(NativeKeyEvent nativeKeyEvent) {
        // 如果启动才监听q按键
        String text = startButton.getText();
        if (STOP_WORD.equals(text)) {
            if (nativeKeyEvent.getKeyCode() == NativeKeyEvent.VC_Q) {
                System.out.println("按了Q....");
                if (skillConfigData == null) {
                    System.out.println("未读取到配置");
                    return;
                }

                List<CustomPoint> pointList = skillConfigData.getPoint();
                if (pointList == null || pointList.size() <= 0) {
                    System.out.println("未读取到坐标配置，请重新配置");
                    return;
                }
                List<SkillInfo> skills = skillConfigData.getSkills();
                if (skills == null || skills.size() <= 0) {
                    System.out.println("未读取到技能配置，请重新配置");
                    return;
                }

                for (SkillInfo skillInfo : skills) {
                    boolean match = true;
                    List<CustomColor> colors = skillInfo.getColor();
                    String skillName = skillInfo.getSkillName();
                    System.out.println("skillName=" + skillName);

                    for (int j = 0; j < colors.size(); j++) {
                        CustomPoint point = pointList.get(j);
                        Color currentColor = robot.getPixelColor(point.getX(), point.getY());
                        System.out.println(currentColor);

                        if (!colors.get(j).compare(currentColor)) {
                            System.out.println("不匹配");
                            match = false;
                            break;
                        }
                    }

                    if (match) {
                        String keyBinding = skillInfo.getKeyBinding();
                        switch (keyBinding) {
                            case "-":
                                robot.keyPress(KeyEvent.VK_MINUS);
                                robot.keyRelease(KeyEvent.VK_MINUS);
                                break;
                            case "=":
                                robot.keyPress(KeyEvent.VK_EQUALS);
                                robot.keyRelease(KeyEvent.VK_EQUALS);
                                break;
                            case "0":
                                robot.keyPress(KeyEvent.VK_0);
                                robot.keyRelease(KeyEvent.VK_0);
                                break;
                            case "1":
                                robot.keyPress(KeyEvent.VK_1);
                                robot.keyRelease(KeyEvent.VK_1);
                                break;
                            case "2":
                                robot.keyPress(KeyEvent.VK_2);
                                robot.keyRelease(KeyEvent.VK_2);
                                break;
                            case "3":
                                robot.keyPress(KeyEvent.VK_3);
                                robot.keyRelease(KeyEvent.VK_3);
                                break;
                            case "4":
                                robot.keyPress(KeyEvent.VK_4);
                                robot.keyRelease(KeyEvent.VK_4);
                                break;
                            case "5":
                                robot.keyPress(KeyEvent.VK_5);
                                robot.keyRelease(KeyEvent.VK_5);
                                break;
                            case "6":
                                robot.keyPress(KeyEvent.VK_6);
                                robot.keyRelease(KeyEvent.VK_6);
                                break;
                            case "7":
                                robot.keyPress(KeyEvent.VK_7);
                                robot.keyRelease(KeyEvent.VK_7);
                                break;
                            case "8":
                                robot.keyPress(KeyEvent.VK_8);
                                robot.keyRelease(KeyEvent.VK_8);
                                break;
                            case "9":
                                robot.keyPress(KeyEvent.VK_9);
                                robot.keyRelease(KeyEvent.VK_9);
                                break;
                            case "F":
                                robot.keyPress(KeyEvent.VK_F);
                                robot.keyRelease(KeyEvent.VK_F);
                                break;
                            case "R":
                                robot.keyPress(KeyEvent.VK_R);
                                robot.keyRelease(KeyEvent.VK_R);
                                break;
                            default:
                        }
                        break;
                    }
                }
            }

            if (nativeKeyEvent.getKeyCode() == NativeKeyEvent.VC_E) {
                System.out.println("按了E....");
                if (skillAoeConfigData == null) {
                    System.out.println("未读取到配置");
                    return;
                }

                List<CustomPoint> pointList = skillAoeConfigData.getPoint();
                if (pointList == null || pointList.size() <= 0) {
                    System.out.println("未读取到坐标配置，请重新配置");
                    return;
                }
                List<SkillInfo> skills = skillAoeConfigData.getSkills();
                if (skills == null || skills.size() <= 0) {
                    System.out.println("未读取到技能配置，请重新配置");
                    return;
                }

                for (SkillInfo skillInfo : skills) {
                    boolean match = true;
                    List<CustomColor> colors = skillInfo.getColor();
                    String skillName = skillInfo.getSkillName();
                    System.out.println("skillName=" + skillName);

                    for (int j = 0; j < colors.size(); j++) {
                        CustomPoint point = pointList.get(j);
                        Color currentColor = robot.getPixelColor(point.getX(), point.getY());
                        //System.out.println(currentColor);

                        if (!colors.get(j).compare(currentColor)) {
                            //System.out.println("不匹配");
                            match = false;
                            break;
                        }
                    }

                    if (match) {
                        String keyBinding = skillInfo.getKeyBinding();
                        switch (keyBinding) {
                            case "-":
                                robot.keyPress(KeyEvent.VK_MINUS);
                                robot.keyRelease(KeyEvent.VK_MINUS);
                                break;
                            case "=":
                                robot.keyPress(KeyEvent.VK_EQUALS);
                                robot.keyRelease(KeyEvent.VK_EQUALS);
                                break;
                            case "0":
                                robot.keyPress(KeyEvent.VK_0);
                                robot.keyRelease(KeyEvent.VK_0);
                                break;
                            case "1":
                                robot.keyPress(KeyEvent.VK_1);
                                robot.keyRelease(KeyEvent.VK_1);
                                break;
                            case "2":
                                robot.keyPress(KeyEvent.VK_2);
                                robot.keyRelease(KeyEvent.VK_2);
                                break;
                            case "3":
                                robot.keyPress(KeyEvent.VK_3);
                                robot.keyRelease(KeyEvent.VK_3);
                                break;
                            case "4":
                                robot.keyPress(KeyEvent.VK_4);
                                robot.keyRelease(KeyEvent.VK_4);
                                break;
                            case "5":
                                robot.keyPress(KeyEvent.VK_5);
                                robot.keyRelease(KeyEvent.VK_5);
                                break;
                            case "6":
                                robot.keyPress(KeyEvent.VK_6);
                                robot.keyRelease(KeyEvent.VK_6);
                                break;
                            case "7":
                                robot.keyPress(KeyEvent.VK_7);
                                robot.keyRelease(KeyEvent.VK_7);
                                break;
                            case "8":
                                robot.keyPress(KeyEvent.VK_8);
                                robot.keyRelease(KeyEvent.VK_8);
                                break;
                            case "9":
                                robot.keyPress(KeyEvent.VK_9);
                                robot.keyRelease(KeyEvent.VK_9);
                                break;
                            default:
                        }
                        break;
                    }
                }
            }
        }

        // F12整体启停
        if (nativeKeyEvent.getKeyCode() == NativeKeyEvent.VC_F12) {

            javafx.application.Platform.runLater(() -> {
                //System.out.println(text);
                if (START_WORD.equals(text)) {
                    start();
                } else {
                    stop();
                }
            });
        }
    }

    @Override
    public void nativeKeyReleased(NativeKeyEvent nativeKeyEvent) {

    }

    /**
     * 注册键盘监听器
     */
    public void registerKeyListener() {
        try {
            GlobalScreen.addNativeKeyListener(this);
            //System.out.println("配置键盘监听器已注册");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 注销键盘监听器
     */
    public void unregisterKeyListener() {
        GlobalScreen.removeNativeKeyListener(this);
        //System.out.println("配置键盘监听器已注销");
    }

    public String getSelectedTalentLabelText() {
        return selectedTalentLabel.getText();
    }

    @FXML
    public void initialize() throws AWTException {
        //System.out.println("调用了。。");
        robot = new Robot();

        // 初始化标签页和ToggleGroup的映射
        initTabToggleGroupMapping();

        // 添加标签页选择监听
        classTabPane.getSelectionModel().selectedItemProperty().addListener((obs, oldTab, newTab) -> {
            //System.out.println("444" + newTab);
            if (newTab != null) {
                selectedClass = newTab.getText();
                updateSelectedTalentDisplay();
            }
        });

        talentToggleGroup.selectedToggleProperty().addListener((obs, oldToggle, newToggle) -> {
            //System.out.println("3333" + newToggle);
            if (newToggle != null) {
                ToggleButton selectedButton = (ToggleButton) newToggle;
                selectedTalent = selectedButton.getText();
                //System.out.println(111);
                //System.out.println(selectedTalent);
                //System.out.println(222);
                updateSelectedTalentDisplay();
            }
        });
    }

    /**
     * 初始化标签页与ToggleGroup的映射关系
     */
    private void initTabToggleGroupMapping() {
        for (Tab tab : classTabPane.getTabs()) {
            if (tab.getContent() instanceof AnchorPane) {
                AnchorPane anchorPane = (AnchorPane) tab.getContent();
                //System.out.println("anchorPane===" + anchorPane);
                // 在标签页内容中查找 ToggleGroup
                for (Node node : anchorPane.getChildrenUnmodifiable()) {
                    if (node instanceof VBox) {
                        VBox vBox = (VBox) node;
                        //System.out.println("vBox===" + vBox);
                        // 在 VBox 中查找第一个 ToggleButton 获取 ToggleGroup
                        for (Node child : vBox.getChildren()) {
                            if (child instanceof ToggleButton) {
                                ToggleButton toggleButton = (ToggleButton) child;
                                //System.out.println("toggleButton.getText()==" + toggleButton.getText());
                                ToggleGroup group = toggleButton.getToggleGroup();
                                if (group != null) {
                                    //System.out.println("tab==" + tab);
                                    //System.out.println(tab.getText());
                                    //System.out.println("group==" + group);

                                    tabToggleGroupMap.put(tab, group);
                                    //System.out.println("size====" + tabToggleGroupMap.size());
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    private void updateSelectedTalentDisplay() {
        if (!selectedClass.isEmpty() && !selectedTalent.isEmpty()) {
            // 解析天赋文本（格式："大地的裂变-生存"）
            String[] parts = selectedTalent.split("-");
            if (parts.length >= 2) {
                selectedVersion = parts[0];
                selectedTalent = parts[1];
                selectedTalentLabel.setText(selectedClass + "-" + selectedVersion + "-" + selectedTalent);
            } else {
                selectedTalentLabel.setText(selectedClass + "-" + selectedTalent);
            }
        }
    }

    @FXML
    private void handleConfirmButtonAction() {
        //System.out.println(selectedClass);
        //System.out.println("selectedTalent==" + selectedTalent);
        if (!selectedClass.isEmpty() && !selectedTalent.isEmpty()) {
            // 保存配置
            saveSelectedConfig();

            // 显示确认信息
            showCustomDialog("配置保存", "已保存配置: " + selectedTalentLabel.getText());
        } else {
            showCustomDialog("配置错误", "请先选择职业和天赋");
        }
    }

    private void saveSelectedConfig() {
        // 这里实现保存配置的逻辑
        //System.out.println("保存配置: " + selectedTalentLabel.getText());

        // 示例：保存到文件或数据库
        // saveToFile(selectedClass, selectedVersion, selectedTalent);
    }

}
